package practise;

public class DetectCycle {
    public ListNode detectCycle(ListNode head) {
        if(head == null || head.next == null) {
            return null;
        }

        ListNode slow = head;
        ListNode fast = head;
        do {
            slow = slow.next;
            fast = fast.next.next;
            if(slow == fast) {
                break;
            }
        } while (fast != null && fast.next != null);
        if(slow != fast) {
            return null;
        }

        ListNode cur1 = head;
        ListNode cur2 = slow;
        while(cur1 != cur2) {
            cur1 = cur1.next;
            cur2 = cur2.next;
        }
        return cur2;
    }
}
